#include "consolewnd.h"

CConsoleWnd::CConsoleWnd(void)
{
	m_hStdConsole = INVALID_HANDLE_VALUE;
#ifdef _DEBUG
	if (!AllocConsole())
	{
		m_hStdConsole = INVALID_HANDLE_VALUE;
	}

	m_hStdConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	SYSTEMTIME kTime; 
	GetLocalTime(&kTime);
	char acTemp[256] = {0};
	sprintf_s(acTemp,sizeof(acTemp),"%d:%d:%d",kTime.wHour,kTime.wMinute,kTime.wSecond);

	SetConsoleTitle(acTemp);

#endif

	InitializeCriticalSection(&m_kSection);
}

CConsoleWnd::~CConsoleWnd(void)
{
	if (m_hStdConsole != INVALID_HANDLE_VALUE)
	{
		FreeConsole();
	}

	DeleteCriticalSection(&m_kSection);
}



void CConsoleWnd::PrintLog(LPCSTR szLogString /* = "" */)
{
	if (m_hStdConsole == INVALID_HANDLE_VALUE)
	{
		return;
	}
	if (szLogString == NULL)
	{
		return;
	}
	if (strlen(szLogString) <= 0)
	{
		return;
	}

	EnterCriticalSection(&m_kSection);
	SetConsoleTextAttribute(m_hStdConsole,FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE);

	DWORD nLength = 0;
	WriteConsole(m_hStdConsole,szLogString,(DWORD)strlen(szLogString),&nLength,NULL);
	WriteConsole(m_hStdConsole,"\n",(DWORD)strlen("\n"),&nLength,NULL);

	LeaveCriticalSection(&m_kSection);
	return;
}

void CConsoleWnd::PrintFormatLog(LPCSTR szFormat,...)
{
	TCHAR szBuffer[1024] = {0};
	va_list pArgList;

	// The va_start macro (defined in STDARG.H) is usually equivalent to:
	// pArgList = (char *) &szFormat + sizeof (szFormat) ;

	va_start(pArgList,szFormat);

	// The last argument to wvsprintf points to the arguments

	_vsnprintf_s(szBuffer,sizeof(szBuffer) / sizeof(TCHAR),sizeof(szBuffer) / sizeof(TCHAR),szFormat,pArgList);

	// The va_end macro just zeroes out pArgList for no good reason

	va_end(pArgList) ;

	PrintLog(szBuffer);
}

void CConsoleWnd::DiableCloseButton()
{
	if (m_hStdConsole == INVALID_HANDLE_VALUE)
	{
		return;
	}
	char szTittle[255] = {0};
	GetConsoleTitle(szTittle,255);
	HWND hWnd = FindWindow("ConsoleWindowClass",szTittle);
	hWnd = GetConsoleWindow();
	HMENU hMenu = NULL;
	hMenu = GetSystemMenu(hWnd,FALSE);
	RemoveMenu(hMenu,SC_CLOSE,MF_BYCOMMAND);
}

void CConsoleWnd::EnableColseButton()
{

}